
import { error, log } from "cc"

import { BaseStore, BattleMode, cat, computed, CoreStore, create, makeObservable, observable, Room, RoomMode, RoomSchema, SeatStatus } from "../Test"


export class RoomStore extends BaseStore {

    constructor(rootStore: CoreStore) {
        super(rootStore)
        makeObservable(this, {
            roomInfo: observable,
            mode: computed,
            seatStatus: computed,
            roomMode: observable,
        })
    }

    /**房间信息 */
    roomInfo: Room = create(RoomSchema)

    /**游戏模式 */
    get mode() {
        return this.roomInfo?.battleInfo?.mode ?? BattleMode.UNSPECIFIED
    }

    /**用户的座位状态 */
    get seatStatus() {
        return this.userSeat?.status ?? SeatStatus.UNSPECIFIED
    }

    /**用户的座位 */
    get userSeat() {
        return this.roomInfo.seats.find(item => item.user?.uid === this.rootStore.user?.userId)
    }


    /**房间模式 */
    roomMode: RoomMode = RoomMode.None

}


/**离开房间 */
export async function LeaveRoom(is_rematch: boolean = false) {
    const { roomInfo } = cat.store.room
    const { id } = roomInfo
    await cat.room_ws.LeaveRoom(id).then((res) => {
        log('离开房间', res)
        cat.gui.loadScene('lobby', { props: { is_rematch } })
        cat.store.room.roomInfo = create(RoomSchema)
    }).catch((err) => {
        error(err)
        cat.gui.loadScene('lobby')
    })
    cat.gui.showToast({ title: '离开房间' })
}

/**查询房间 */
async function QueryAliveRoom(room_id: string = '') {
    try {
        // 获取房间状态
        cat.gui.showLoading({ title: '获取数据' })
        const res = await cat.room_ws.QueryAliveRoom(room_id)
        log('QueryAliveRoom', res)
        if (res.room) {
            cat.store.room.roomInfo = res.room
        } else {
            cat.store.room.roomInfo = create(RoomSchema)
        }
    } catch (error) {
        cat.store.room.roomInfo = create(RoomSchema)
    }
    cat.gui.hideLoading()
}

globalThis.QueryAliveRoom = QueryAliveRoom

globalThis.LeaveRoom = LeaveRoom


console.log('BUNDLE STORE')